package SqlGenerator;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class TableInfo {
    private String tableName;
    private Class<?> clazz;
    private boolean needPersist=false;
    private Map<String,ColumnInfo> columns = new HashMap<String,ColumnInfo>();
    public boolean removecolumn(String columnname)
    {
        for(ColumnInfo column:this.columns.values()){

            if(column.getColumnName().equals(columnname)){
                columns.remove(column);
                return true;
            }
        }
        return false;
    }
    public boolean samename(Field field){
        for(String columnInfo:columns.keySet()){
            if(columnInfo.equals(field.getName()))
                return true;
        }
        return false;
    }
    public ColumnInfo addcolumn(Field field)
    {
        ColumnInfo column = new ColumnInfo();
        column=column.parse(field);
        if(column!=null){
            this.columns.put(field.getName(),column);
        }
        return column;
    }
    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public TableInfo parse(Class<?> clazz){
        this.clazz = clazz;
        this.tableName=this.clazz.getSimpleName();

        Annotation[] annotations = this.clazz.getAnnotations();
        for(Annotation annotation:annotations){
            if(annotation.annotationType().equals(Entity.class)){
                this.needPersist = true;
                Entity entity = (Entity)annotation;
                if(!entity.value().equals("")){
                    this.tableName = entity.value();

                }
                break;
            }
        }
        if(this.needPersist){
            Field[] fields = this.clazz.getDeclaredFields();
            for(Field field:fields){
                ColumnInfo column = new ColumnInfo();
                column=column.parse(field);
                if(column!=null){
                    this.columns.put(field.getName(),column);
                }
            }
            return this;
        }
        else
            return null;
    }
    public String toString(){
        StringBuilder sql = new StringBuilder();
        sql.append("\nCREATE TABLE ");
        sql.append(this.tableName+" (");
        for(ColumnInfo column:this.columns.values())
            sql.append("\n  "+column.toString());
        sql.append("\b\n);");
        return sql.toString();
    }
}
